function isDate(obj) {
  return obj instanceof Date;
}

/**
 * 获取当前日期的毫秒数
 * @method getTime
 * @param {String} date
 * @return {Number}
 */
function getTime(date) {
  if (isDate(date)) {
    return date.getTime();
  } else {
    try {
      return new Date(date.replace(/-/g, '/')).getTime();
    } catch (e) {
      return 0;
    }
  }
}

/**
 * 是否是今天
 * @method isToday
 * @param {String} date
 * @return {Boolean}
 */
function isToday(today, date) {
  return getTime(today) === getTime(date);
}

/**
 * 检查是否是闰年
 * @method _checkLeapYear
 * @param {Number} y 年份
 * @param {Date} t today
 * @protected
 */
function getMonthDays(y, t) {
  const MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  const year = y || t.getFullYear();
  let isLeapYear = false;

  if (year % 100) {
    isLeapYear = !(year % 4);
  } else {
    isLeapYear = !(year % 400);
  }

  MONTH_DAYS[1] = isLeapYear ? 29 : 28;

  return MONTH_DAYS;
}

function getMonthPadding(year, month, startDay = 0) {
  const date = new Date(year + '/' + month + '/1');
  let day = date.getDay();

  let padding = (day - startDay + 7) % 7;

  return padding;
}

export function getWeekRows(year, month, today, startDay = 0) {
  const monthDays = getMonthDays(year, today);
  const padding = getMonthPadding(year, month, startDay);
  const num = monthDays[month - 1] + padding;
  const rows = Math.ceil(num / 7);
  const remain = num % 7;
  const rowsData = [];

  for (let i = 1; i <= rows; i++) {
    const cells = [];

    for (let j = 1; j <= 7; j++) {
      let cell = {};
      // 前后空格
      let cls = [];
      if (i === 1 && j <= padding) {
        cls.push('day-prev-month');
        const date = new Date(year + '/' + month + '/1');
        date.setDate(date.getDate() - (padding - j + 1));
        cell = {
          isPrev: true,
          cls: cls,
          date: date,
          text: date.getDate(),
        };
      } else if (remain && i === rows && j > remain) {
        cls.push('day-next-month');
        const date = new Date(year + '/' + month + '/' + monthDays[month - 1]);
        date.setDate(date.getDate() + (j - remain));
        cell = {
          isNext: true,
          cls: cls,
          date: date,
          text: date.getDate(),
        };
      } else {
        const d = (i - 1) * 7 + j - padding;
        const date = year + '/' + month + '/' + d;

        if (isToday(today, date)) {
          cls.push('calendar-today');
        }

        cell = {
          cls: cls,
          date: new Date(date),
          text: d
        };
      }
      cells.push(cell);
    }

    rowsData.push(cells);
  }

  return rowsData;
}
